from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import User
import re
import string
import random
from captcha.image import ImageCaptcha
from django.http import HttpResponse
import redis

from django.contrib.auth.hashers import check_password
import jwt
from django.conf import settings
import time
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler
from django.db import models

# 校验用户名是否重复
class CheckUsername(APIView):
    def get(self,request,username):
        # 查询当前用户名是否存在
        try:
            user =User.objects.get(username=username)
        except:
            return Response({"code":200,"msg":"用户名可以使用"})
        return Response({"code":204,"msg":"用户名已注册"})

# 检验手机号的重复性
class CheckMobile(APIView):
    def get(self,request,mobile):
        # 验证手机号 是否满足规则
        if not re.findall(r"^1[3-9]\d{9}$",mobile):
            return Response({"code":204,"msg":"手机号不合法"})
        user_query_set=User.objects.filter(mobile=mobile)
        if not user_query_set:
            return Response({"code":200,"msg":"可以正常注册"})
        return Response({"code":200,'msg':'手机号已注册'})


# 图片验证码
class GenImageCode(APIView):
    def get(self, request, uuid):
        # 1.生成随机字符串
        alpha_number = string.ascii_letters + string.digits
        img_code = "".join(random.sample(alpha_number, 4))
        # 2.生成图片验证码
        img_cap = ImageCaptcha()
        img_cap.generate(img_code)
        img_code_captcha = img_cap.generate(img_code)

        # 3.存储图片验证码
        redis_conn=redis.Redis(host='localhost',port=6379,db=0)
        key = "image_code:%s" % uuid
        redis_conn.set(key, img_code, ex=300)
        redis_conn.close()
        return HttpResponse(img_code_captcha, content_type="image/png")

# 效验图片验证码
class CheckImageCode(APIView):
    def get(self, request):
        # 1.获取前端数据
        uuid_ = request.query_params.get('imageCodeID')
        image_code = request.query_params.get('imageCode')
        # 2.根据uuid 构造key
        key = 'image_code:%s' % uuid_
        # 3.读取redis存储的验证码
        redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        stored_image_code = redis_conn.get(key)
        if not stored_image_code:
            return Response({'code': 204, 'msg': '图片验证码已过期'})
        print('验证码：', stored_image_code)
        if stored_image_code.decode().lower() == image_code.lower():
            return Response({'code': 200, 'msg': '验证成功'})

# 用户注册
class Register(APIView):
    def post(self,request):
        # 1.获取前端数据
        username = request.data.get('userName')
        password = request.data.get('pwd')
        # confirm_password = request.data.get('pass')
        mobile = request.data.get('mobile')
        aggrement = request.data.get('agree')
        # 2.简单验证
        if not all([username,password,mobile,aggrement]):
            return Response({'code':204,'msg':'用户信息不完整'})
        # 3.创建用户对象，并存储
        User.objects.create_user(username=username,password=password,mobile=mobile)
        return Response({'code':200,'msg':'注册成功'})




# 用户登录
class Login(APIView):
    def post(self,request):
        # 获取前端数据
        username =request.data.get("user")
        password =request.data.get("pwd")
        # 查询用户
        try:
            user = User.objects.get(models.Q(username=username)|models.Q(mobile=username))
        except:
            return Response({"code":204,"msg":"用户不存在"})
        # 验证密码
        validate =check_password(password,user.password)
        if validate:
            # 验证通过允许登录
            # request.session['username'] =username
            token = self.gen_token(user)

            return Response({"code":200,"msg":"欢迎%s"%username,'user':{"userName":user.username},'token':token})
        return Response({"code":204,"msg":"用户名或密码错误"})

    @staticmethod
    def gen_token(user):
        # 使用jwt编码，生成token
        payload ={
            "username":user.username,
            "exp":time.time() + 300
        }
        token =jwt.encode(payload=payload,key=settings.SECRET_KEY,algorithm='HS256')
        return token


# 退出登录
class Logout(APIView):
    def get(self,request):
        if request.session.get("username"):
            # 删除服务端session
            del request.session["username"]
        return Response({"code":200,"msg":"退出登录"})










